#封装数据库操作类
import logging

import pymysql

class DBUtil(object):
    #添加类属性
    conn = None

    @classmethod
    def __get_connect(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="192.168.191.164", port=3306, user="root", password="123456",
                               database="egowx", charset="utf8")
        return cls.conn

    @classmethod
    def __close_connect(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    #常用方法：查询1条
    @classmethod
    def select_one(cls,sql):
        cursor = None
        res = None

        try:
            #获取连接
            cls.conn = cls.__get_connect()

            #获取游标
            cursor = cls.conn.cursor()

            #执行查询语句
            cursor.execute(sql)

            #提取1条结果
            res = cursor.fetchone()

        except Exception as e:
            print("查询sql错误：",str(e))

        finally:
            cursor.close()
            cls.__close_connect()
            #将执行查询的结果返回
            return res

    #常用方法：增删改
    @classmethod
    def uid_db(cls,sql):
        cursor = None

        try:
        #创建连接
            cls.conn =  cls.__get_connect()
        #获取游标
            cursor = cls.conn.cursor()
        #执行语句
            cursor.execute(sql)
            # print("被影响的行数：",cls.conn.affected_rows())
            logging.info(f"影响的行数：{cls.conn.affected_rows()}")
        #提交事务
            cls.conn.commit()

        except Exception as e:
            # print("执行增删改语句失败：",str(e))
            logging.error(f"执行增删改语句失败:{str(e)}")
            cls.conn.rollback()

        finally:
            #关闭游标
                cursor.close()
            #关闭连接
                cls.__close_connect()


if __name__ == '__main__':
    res = DBUtil.select_one("select * from product where id = 1;")
    print("查询结果为：",res)

    DBUtil.uid_db("update product set name='猜0' where id =1;")
    DBUtil.uid_db("delete from user_address where mobile = '18800000001'")



